import { defineStore } from 'pinia'
import { ref } from 'vue'
import { showToast } from 'vant'
import {
  getFileList,
  createFolder,
  deleteFile,
  renameFile,
  moveFile,
  getStorageInfo,
  type FileInfo,
  type FileListParams,
  type StorageInfoResponse
} from '@/api/file'

export const useFileStore = defineStore('file', () => {
  // 状态
  const fileList = ref<FileInfo[]>([])
  const currentFolderId = ref<number>(0)
  const loading = ref<boolean>(false)
  const pagination = ref({
    total: 0,
    page: 1,
    size: 20,
    pages: 0
  })
  const breadcrumbList = ref<{ id: number; name: string }[]>([])
  const storageInfo = ref<StorageInfoResponse | null>(null)

  // 获取文件列表
  const fetchFileList = async (params?: Partial<FileListParams>) => {
    try {
      loading.value = true

      const requestParams: FileListParams = {
        parentId: currentFolderId.value,
        page: pagination.value.page,
        size: pagination.value.size,
        orderBy: 'updateTime',
        orderType: 'desc',
        ...params
      }

      const response = await getFileList(requestParams)

      fileList.value = response.content
      pagination.value = {
        total: response.totalElements || response.total || 0,
        page: (response.number !== undefined ? response.number + 1 : response.page) || 1,
        size: response.size || 20,
        pages: response.totalPages || response.pages || 1
      }


      return response
    } catch (error) {
      console.error('获取文件列表失败:', error)
      fileList.value = [] // 确保在错误时清空列表
      throw error
    } finally {
      loading.value = false
    }
  }

  // 进入文件夹
  const enterFolder = async (folder: FileInfo) => {
    if (folder.isFolder === 1) {
      currentFolderId.value = folder.id
      breadcrumbList.value.push({
        id: folder.id,
        name: folder.fileName
      })
      pagination.value.page = 1
      await fetchFileList()
    }
  }

  // 返回上级目录
  const goBack = async () => {
    if (breadcrumbList.value.length > 0) {
      breadcrumbList.value.pop()
      if (breadcrumbList.value.length > 0) {
        const parentFolder = breadcrumbList.value[breadcrumbList.value.length - 1]
        currentFolderId.value = parentFolder?.id || 0
      } else {
        currentFolderId.value = 0
      }
      pagination.value.page = 1
      await fetchFileList()
    }
  }

  // 导航到指定文件夹
  const navigateToFolder = async (folderId: number, breadcrumbIndex?: number) => {
    currentFolderId.value = folderId

    if (breadcrumbIndex !== undefined) {
      breadcrumbList.value = breadcrumbList.value.slice(0, breadcrumbIndex + 1)
    } else if (folderId === 0) {
      breadcrumbList.value = []
    }

    pagination.value.page = 1
    await fetchFileList()
  }

  // 创建文件夹
  const createNewFolder = async (folderName: string) => {
    try {
      await createFolder(folderName, currentFolderId.value)
      showToast({
        type: 'success',
        message: '文件夹创建成功'
      })
      await fetchFileList()
    } catch (error) {
      console.error('创建文件夹失败:', error)
      throw error
    }
  }

  // 删除文件
  const removeFile = async (fileId: number) => {
    try {
      await deleteFile(fileId)
      showToast({
        type: 'success',
        message: '删除成功'
      })
      await fetchFileList()
      await fetchStorageInfo()
    } catch (error) {
      console.error('删除文件失败:', error)
      throw error
    }
  }

  // 重命名文件
  const renameFileItem = async (fileId: number, newName: string) => {
    try {
      await renameFile(fileId, newName)
      showToast({
        type: 'success',
        message: '重命名成功'
      })
      await fetchFileList()
    } catch (error) {
      console.error('重命名失败:', error)
      throw error
    }
  }

  // 移动文件
  const moveFileItem = async (fileId: number, targetParentId: number) => {
    try {
      await moveFile(fileId, targetParentId)
      showToast({
        type: 'success',
        message: '移动成功'
      })
      await fetchFileList()
    } catch (error) {
      console.error('移动文件失败:', error)
      throw error
    }
  }

  // 获取存储信息
  const fetchStorageInfo = async () => {
    try {
      const info = await getStorageInfo()
      storageInfo.value = info
      return info
    } catch (error) {
      console.error('获取存储信息失败:', error)
      throw error
    }
  }

  // 刷新当前列表
  const refreshFileList = () => {
    return fetchFileList()
  }

  // 重置状态
  const resetState = () => {
    fileList.value = []
    currentFolderId.value = 0
    breadcrumbList.value = []
    pagination.value = {
      total: 0,
      page: 1,
      size: 20,
      pages: 0
    }
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B'

    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化时间
  const formatTime = (time: string): string => {
    return new Date(time).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  return {
    // 状态
    fileList,
    currentFolderId,
    loading,
    pagination,
    breadcrumbList,
    storageInfo,

    // 方法
    fetchFileList,
    enterFolder,
    goBack,
    navigateToFolder,
    createNewFolder,
    removeFile,
    renameFileItem,
    moveFileItem,
    fetchStorageInfo,
    refreshFileList,
    resetState,
    formatFileSize,
    formatTime
  }
})